class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n;)
        {
            for (int j = i + 1; j < n;)
            {

                int left = j + 1, right = nums.size() - 1;
                long long aim = (long long)target - nums[i] - nums[j];
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum > aim) right--;
                    else if (sum < aim) left++;
                    else
                    {
                        ret.push_back({ nums[i],nums[left++],nums[right--],nums[j] });
                        while (left < right && nums[left - 1] == nums[left]) left++;
                        while (left < right && nums[right] == nums[right + 1]) right--;
                    }

                }
                j++;
                while (j < n && nums[j - 1] == nums[j]) j++;
            }
            i++;
            while (i < n && nums[i - 1] == nums[i])i++;
        }
        return ret;

    }
};